﻿using AutoMapper;
using B.S.Filtration.Domain.到货检验;
using B.S.Filtration.ErrorCode;
using B.S.Filtration.Write.Api.Application.Command.到货检验.QualityLnspectionCommnad;
using MediatR;
using SqlSugar;

namespace B.S.Filtration.Write.Api.Application.CommandHander.到货检验.QualityLnspectionHandler
{
    /// DelQualityLnspectionHandler：这是一个处理 DelQualityLnspectionCommnad 请求的类，继承自 IRequestHandler 接口。
    public class DelQualityLnspectionHandler : IRequestHandler<DelQualityLnspectionCommnad, APIResult<int>>
    {
        //ISqlSugarClient ：这是一个 SQLSugar 的数据库客户端接口，用于执行数据库操作。
        private readonly ISqlSugarClient db;
        //IMapper：这是 AutoMapper 库 的核心接口，用于对象映射。
        private readonly IMapper mapper;
        //构造函数：DelQualityLnspectionHandler，接收两个参数 db 和 mapper。
        public DelQualityLnspectionHandler(ISqlSugarClient db, IMapper mapper)
        {
            this.db = db;
            this.mapper = mapper;
        }
        public async Task<APIResult<int>> Handle(DelQualityLnspectionCommnad request, CancellationToken cancellationToken)
        {
            APIResult<int> result = new APIResult<int>();
            var list = await db.Queryable<QualityLnspection>().FirstAsync(x => x.Qualityid == request.Qualityid);

            // 增加判空逻辑
            if (list == null)
            {
                result.code = APIResultCode.failed;
                result.msg = "未找到要删除的信息";
                return result;
            }

            list.IsDel = true;
            result.data = await db.Updateable<QualityLnspection>(list).ExecuteCommandAsync();
            if (result.data > 0)
            {
                result.code = APIResultCode.success;
                result.msg = "删除成功";
            }
            else
            {
                result.code = APIResultCode.failed;
                result.msg = "删除失败";
            }
            return result;
        }
    }
}
